package org.example.curriculum_design_6_16.common.handler;

import jakarta.servlet.http.HttpServletRequest;
import org.example.curriculum_design_6_16.common.base.BaseException;
import org.example.curriculum_design_6_16.common.system.SystemException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BaseException.class)
    public ResponseEntity<ErrorResult> handleBaseException(
            BaseException ex,
            HttpServletRequest request) {
        return ResponseEntity
                .status(ex.getHttpStatus())
                .body(ErrorResult.of(ex, request.getRequestURI()));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResult> handleUnknownException(
            Exception ex,
            HttpServletRequest request) {
        SystemException systemEx = new SystemException("SYS_000", "系统繁忙");
        return ResponseEntity
                .status(500)
                .body(ErrorResult.of(
                        systemEx.withDetail(ex.getMessage()),
                        request.getRequestURI()
                ));
    }
}